package cn.kgc.config;

import cn.kgc.listener.DeadLetterMessageListener;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author YC
 * 注解@ConditionalOnProperty(value = "mq.enableHandleDlx") 配置文件中配置mq.enableHandleDlx=true则使用此配置类
 */
@Configuration
@ConditionalOnProperty(value = "mq.enableHandleDlx")
public class RabbitDeadLetterConfig {

    @Value("${mq.deadQueueName}")
    private String deadQueueName;
    @Value("${mq.deadExchangeName}")
    private String deadExchangeName;
    @Value("${mq.deadRoutingKey}")
    private String deadRoutingKey;

    /**
     * 死信队列
     * new Queue(String name队列名称, boolean durable是否持久化, boolean exclusive是否排他性, boolean autoDelete是否自动删除)
     */
    @Bean
    public Queue deadQueue() {
        return new Queue(deadQueueName, true, false, false);
    }

    /**
     * 死信交换机
     * new DirectExchange(String name交换机名称, boolean durable是否持久化, boolean autoDelete是否自动删除)
     */
    @Bean
    public DirectExchange deadExchange() {
        return new DirectExchange(deadExchangeName, true, false);
    }

    /**
     * 死信队列绑定
     * BindingBuilder.bind(Queue queue).to(Exchange exchange).with(String routingKey路由键)
     */
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(deadRoutingKey);
    }

    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer(
            ConnectionFactory connectionFactory, DeadLetterMessageListener deadLetterMessageListener
    ) {
        SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setExposeListenerChannel(true);
        //死信队列的名字
        listenerContainer.setQueueNames(deadQueueName);
        //监听死信队列的监听器
        listenerContainer.setMessageListener(deadLetterMessageListener);
        //信息手动确认
        listenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return listenerContainer;
    }

}
